package org.example.contain;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class EffectiveCache2 {
    //用来存储缓存对象
    private static final Map<String, FutureTask<Object>> cache = new ConcurrentHashMap<>();

    //获取需要的缓存对象,不存在就创建一个
    public Object getOne(String key) throws ExecutionException, InterruptedException {
        FutureTask<Object> ft = cache.get(key);
        if (ft == null) {
            FutureTask<Object> f = new FutureTask<>(() -> produce(key));
            //如果对应的key不存在时返回null的
            ft = cache.putIfAbsent(key, f);
            if (ft == null) {
                ft = f;
                ft.run();
            }
        }
        return ft.get();
    }

    private Object produce(String key) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Object();
    }

    public static void main(String[] args) {

    }
}